package pl.register.android.database.crud;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import pl.register.android.chapter.ChapterTitle;
import pl.register.android.database.tables.ChapterTitleDBTable;
import pl.register.android.lesson.LessonProgram;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-26
 */
public class ChapterTitleCRUD {

    private SQLiteDatabase database;

    public ChapterTitleCRUD(SQLiteDatabase database) {
        this.database = database;
    }

    public ChapterTitle findChapterBy(LessonProgram lessonProgram) {
        ChapterTitle chapter = null;
        String where = ChapterTitleDBTable.FK_LESSON_PROGRAM_ID + " = " + lessonProgram.getId();
        Cursor cursor = database.query(ChapterTitleDBTable.TABLE_NAME, null, where, null, null, null, null);
        if (cursor.moveToFirst()) {
            Long chapterId = cursor.getLong(cursor.getColumnIndex(ChapterTitleDBTable.ID));
            String chapterTitle = cursor.getString(cursor.getColumnIndex(ChapterTitleDBTable.TITLE));
            chapter = new ChapterTitle(chapterId, chapterTitle);
        }
        cursor.close();
        return chapter;
    }

    public ChapterTitle insertChapter(ChapterTitle chapter, LessonProgram lessonProgram) {
        ContentValues insertValues = new ContentValues();
        insertValues.put(ChapterTitleDBTable.TITLE, chapter.getTitle());
        insertValues.put(ChapterTitleDBTable.FK_LESSON_PROGRAM_ID, lessonProgram.getId());
        long rowId = database.insert(ChapterTitleDBTable.TABLE_NAME, null, insertValues);
        chapter.setId(rowId);
        return chapter;
    }

    public ChapterTitle updateChapterTitle(ChapterTitle chapter) {
        String where = ChapterTitleDBTable.ID + " = " + chapter.getId();
        ContentValues updateValues = new ContentValues();
        updateValues.put(ChapterTitleDBTable.TITLE, chapter.getTitle());
        database.update(ChapterTitleDBTable.TABLE_NAME, updateValues, where, null);
        return chapter;
    }

}